package com.github.editor.util;

import java.io.*;

public class FileUtil {

    public static boolean delete(String path) {
        if (TextUtils.isEmpty(path)) {
            return false;
        }
        File file = new File(path);
        return file.exists() && file.delete();
    }

    public static String getName(String path) {
        if (path == null) {
            return "";
        }
        int index = path.lastIndexOf('/');
        if (index >= 0) {
            path = path.substring(index + 1);
        }
        index = path.lastIndexOf('\\');
        if (index >= 0) {
            path = path.substring(index + 1);
        }
        return path;
    }

    public static String getNameNoEx(String path) {
        String name = getName(path);
        int index = name.lastIndexOf('.');
        if (index > 0) {
            return name.substring(0, index);
        }
        return name;
    }

    public static long copy(InputStream inputStream, OutputStream outputStream) throws IOException {
        long count = 0;
        byte[] data = new byte[1204 * 4];
        int len;
        while ((len = inputStream.read(data)) != -1) {
            outputStream.write(data, 0, len);
            count += len;
        }
        return count;
    }

    public static byte[] ReadAllBytes(String path) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try (FileInputStream inputStream = new FileInputStream(path)) {
            copy(inputStream, outputStream);
        }
        return outputStream.toByteArray();
    }
}
